package org.jeecg.modules.drive.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.*;
import com.ctg.ag.sdk.biz.aep_device_command.CancelCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.QueryCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_event.QueryDeviceEventListRequest;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceListRequest;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_model.QueryPropertyListRequest;
import com.ctg.ag.sdk.biz.aep_device_model.QueryServiceListRequest;
import com.ctg.ag.sdk.biz.aep_device_status.QueryDeviceStatusListRequest;
import com.ctg.ag.sdk.biz.aep_device_status.QueryDeviceStatusRequest;
import com.ctg.ag.sdk.biz.aep_product_management.QueryProductListRequest;
import com.ctg.ag.sdk.biz.aep_product_management.QueryProductRequest;
import com.ctg.ag.sdk.core.model.BaseApiResponse;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.drive.service.IDriveCtwingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 接口驱动模型-天翼Aiot
 *
 */
@Service
public class DriveCtwingServiceImpl implements IDriveCtwingService {


    @Autowired
    private RedisUtil redisUtil;

    /**-------------------------------------------产品--------------------------------------------------------*/
    /**
     * 根据产品ID查询产品数据
     *
     * @param appKey
     * @param appSecret
     * @param productId
     * @throws Exception
     */
    @Override
    public JSONObject sdkNbQueryProduct(String appKey, String appSecret, String productId) throws Exception {
        AepProductManagementClient client = AepProductManagementClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryProductRequest request = new QueryProductRequest();
        request.setParamProductId(productId);	// single value
        BaseApiResponse response = client.QueryProduct(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**
     * 批量查询产品信息
     * 访问路径：/products
     * 请求方法：GET
     *
     * @param appKey
     * @param appSecret
     * @param searchValue
     * @param pageNow
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject sdkNbQueryProductList(String appKey, String appSecret, String searchValue, int pageNow, int pageSize) throws Exception {
        AepProductManagementClient client = AepProductManagementClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();
        QueryProductListRequest request = new QueryProductListRequest();
        BaseApiResponse response = client.QueryProductList(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**-----------------------------------------------设备--------------------------------------------------------*/
    /**
     * 查询设备信息
     * 访问路径：/device
     * 请求方法：GET
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param productId
     * @param deviceId
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject sdkNbQueryDevice(String appKey, String appSecret, String masterKey,
                                       String productId, String deviceId) throws Exception {
        AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryDeviceRequest request = new QueryDeviceRequest();
        request.setParamMasterKey(masterKey);	// single value
        request.setParamProductId(productId);	// single value
        request.setParamDeviceId(deviceId);	// single value
        BaseApiResponse response = client.QueryDevice(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**
     * 批量获取设备信息
     * 访问路径：/devices
     * 请求方法：GET
     *
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param productId
     * @param searchValue
     * @param pageNow
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject sdkNbQueryDeviceList(String appKey, String appSecret, String masterKey, String productId,
                                           String searchValue, int pageNow, int pageSize) throws Exception {
        AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();
        QueryDeviceListRequest request = new QueryDeviceListRequest();
        request.setParamMasterKey(masterKey);	// single value
        request.setParamProductId(productId);	// single value
        request.setParamSearchValue(searchValue);	// single value
        request.setParamPageNow(pageNow);	// single value
        request.setParamPageSize(pageSize);	// single value

        BaseApiResponse response = client.QueryDeviceList(request);
        String s = new String(response.getBody());
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }


    /**-----------------------------------------------事件上报-----------------------------------------------------*/
    /**
     * 查询事件上报列表
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param paramJson  == request.setBody(paramJson.toJSONString().getBytes())
     * {
     *    "productId":"10000088",//必填
     *    "deviceId":"10000088001",//必填
     *    "eventType":1,//非必填
     *    "startTime":"1538981624878",//必填
     *    "endTime":"1539575396505",//必填
     *    "pageSize":10,//必填
     *    "pageTimestamp":"1539575396505"//非必填
     * }
     * //eventType:（int）LWM2M,MQTT,TUP协议可选填: 1：信息 2：警告 3：故障
     *                   T-link协议可选填: 1：告警事件(普通级) 2：告警事件(重大级) 3：告警事件(严重级)；匹配所有事件类型可不填写该参数。
     *
     * //pageTimestamp:可传空或者等于endTime，表示倒序查询的下一页起始时间，每次查询返回pageTimestamp，表示下一页第一条数据的上报时间，
     *            为空则代表没有下一页数据。下次查询带上pageTimestamp参数，即查询startTime - pageTimestamp之间的数据，可实现分页查询。
     * //startTime与endTime之间的时间差最大为31天
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject sdkNbQueryDeviceEventList(String appKey, String appSecret, String masterKey,
                                                JSONObject paramJson) throws Exception {
        AepDeviceEventClient client = AepDeviceEventClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryDeviceEventListRequest request = new QueryDeviceEventListRequest();
        request.setParamMasterKey(masterKey);	// single value
        String body = paramJson.toJSONString();
        request.setBody(body.getBytes());
        BaseApiResponse response = client.QueryDeviceEventList(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**-----------------------------------------------指令下发-----------------------------------------------------*/
    /**
     * 统一合并指令下发
     * 访问路径：/command
     * 请求方法：POST
     *
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param paramJson == request.setBody(paramJson.toJSONString().getBytes())
     * {
     *   "content": {}, 指令内容，必填，格式为Json。
     *   "deviceId": "string", 设备ID，（当指令级别为设备级时必填，为设备组级时则不填）
     *   "operator": "string", 操作者，必填
     *   "productId": 0,产品ID，必填
     *   "ttl": 7200,设备指令缓存时长，选填。单位：秒，取值范围：0-864000。不携带则默认值：7200。如不需缓存请填0。
     *   "deviceGroupId": 100,设备组ID，选填，当指令级别为设备级，deviceId不为空，deviceGroupId为空；
     *   "level": 1 指令级别，1或2为设备级别,3为设备组级别，选填。不填默认设备级。
     * }
     *   content填写样例:
     *          TCP和LWM2M协议透传的content内容：
     *          {
     *              payload:指令内容,数据格式为十六进制时需要填十六进制字符串,
     *              dataType:数据类型：1字符串，2十六进制
     *          }
     *          样例：
     *          {
     *              "dataType":1,
     *              "payload": "5365ab32d"
     *          }
     *          MQTT、TCP和LWM2M协议脚本解析的content内容：
     *          {
     *              dataType:数据类型：1字符串，2十六进制,
     *              payload:指令内容,数据格式为十六进制时需要填十六进制字符串
     *          }
     *
     * @param contentJson
     * @return
     */
    @Override
    public JSONObject sdkNbCreateCommand(String appKey, String appSecret, String masterKey,
                                         JSONObject paramJson, JSONObject contentJson) throws Exception {
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        CreateCommandRequest request = new CreateCommandRequest ();
        request.setParamMasterKey(masterKey);	// MasterKey
        paramJson.put("content", contentJson);
        request.setBody(paramJson.toJSONString().getBytes());
        BaseApiResponse response = client.CreateCommand(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**
     * 查询单个指令详情
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param productId
     * @param deviceId
     * @param commandId
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject sdkNbQueryCommand(String appKey, String appSecret, String masterKey,
                                        String productId, String deviceId,String commandId) throws Exception {
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryCommandRequest request = new QueryCommandRequest  ();
        request.setParamMasterKey(masterKey);
        request.setParamProductId(productId);
        request.setParamDeviceId(deviceId);
        request.setParamCommandId(commandId);

        BaseApiResponse response = client.QueryCommand(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**
     * 取消指令
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param paramJson == request.setBody(paramJson.toJSONString().getBytes())
     * {
     *   "commandId": "a5c71cfcc5074a2f846e26f2988b57b4",指令ID，String,
     *   "deviceId": "c0cda6dd6c52446ba1a0d2a5d26d231a",设备ID，String,
     *   "productId": 10004101  产品Id，Integer
     * }
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject sdkNbCancelCommand(String appKey, String appSecret, String masterKey, JSONObject paramJson) throws Exception {

        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        CancelCommandRequest request = new CancelCommandRequest   ();
        request.setParamMasterKey(masterKey);
        request.setBody(paramJson.toJSONString().getBytes());
        BaseApiResponse response = client.CancelCommand(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }


    /**-----------------------------------------------数据查询-----------------------------------------------------*/
    /**
     * 批量获取设备最新状态数据接口
     * @param appKey
     * @param appSecret
     * @param paramJson == request.setBody(paramJson.toJSONString().getBytes())
     * {
     *  "productId":"3238",
     *  "deviceId":"1da54369fec54dfebce4accc69e9f338"
     *  }
     * @return
     */
    @Override
    public JSONObject sdkNbQueryDeviceStatusList(String appKey, String appSecret, JSONObject paramJson) throws Exception {
        AepDeviceStatusClient client = AepDeviceStatusClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryDeviceStatusListRequest request = new QueryDeviceStatusListRequest();
        request.setBody(paramJson.toJSONString().getBytes());
        BaseApiResponse response = client.QueryDeviceStatusList(request);
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**
     * 终端单个最新状态查询接口
     * @param appKey
     * @param appSecret
     * @param paramJson == request.setBody(paramJson.toJSONString().getBytes())
     * {
     *    "productId":"3238",
     *    "deviceId":"1da54369fec54dfebce4accc69e9f338",
     *    "datasetId":"temperature"  datasetId为待查询的设备上报消息中某个属性标识,透传数据datasetId为"APPdata"
     * }
     *
     * @return
     */
    @Override
    public JSONObject sdkNbQueryDeviceStatus(String appKey, String appSecret, JSONObject paramJson) throws Exception {
        AepDeviceStatusClient client = AepDeviceStatusClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryDeviceStatusRequest request = new QueryDeviceStatusRequest ();
        request.setBody(paramJson.toJSONString().getBytes());
        BaseApiResponse response = client.QueryDeviceStatus(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /***-----------------------------------------------物模型*-----------------------------------------------*/
    /**
     * 查询属性列表信息
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param productId
     * @param searchValue 可填值：属性名称，属性标识符
     * @param pageNow
     * @param pageSize
     * @return
     */
    @Override
    public JSONObject sdkNbQueryPropertyList(String appKey, String appSecret, String masterKey, String productId,
                                             String searchValue, int pageNow, int pageSize) throws Exception {
        AepDeviceModelClient client = AepDeviceModelClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryPropertyListRequest request = new QueryPropertyListRequest();
        request.setParamMasterKey(masterKey);	// MasterKey
        request.setParamProductId(productId);	// MasterKey
        request.setParamSearchValue(searchValue);	// single value
        request.setParamPageNow(pageNow);	// single value
        request.setParamPageSize(pageSize);	// single value

        BaseApiResponse response = client.QueryPropertyList(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }

    /**
     * 查询服务列表信息
     * @param appKey
     * @param appSecret
     * @param masterKey
     * @param productId
     * @param searchValue 可填： 服务Id, 服务名称,服务标识符
     * @param serviceType 服务类型 1. 数据上报 2. 事件上报 3.数据获取 4.参数查询 5.参数配置 6.指令下发 7.指令下发响应
     * @param pageNow
     * @param pageSize
     * @return
     */
    @Override
    public JSONObject sdkNbQueryServiceList(String appKey, String appSecret, String masterKey, String productId,
                                            String searchValue, int serviceType, int pageNow, int pageSize) throws Exception {
        AepDeviceModelClient client = AepDeviceModelClient.newClient()
                .appKey(appKey).appSecret(appSecret)
                .build();

        QueryServiceListRequest request = new QueryServiceListRequest();
        // set your request params here
        request.setParamMasterKey(masterKey);
        request.setParamProductId(productId);
        request.setParamSearchValue(searchValue);
        request.setParamServiceType(serviceType);
        request.setParamPageNow(pageNow);
        request.setParamPageSize(pageSize);
        BaseApiResponse response = client.QueryServiceList(request);
        client.shutdown();
        return JSONObject.parseObject(new String(response.getBody()));
    }
}
